package cn.crdeng.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* cn.crdeng.controller.*.*(..))")
    private  void pt(){}

    @Before("pt()")
    public void doBefrom(JoinPoint joinPoint){
        /*获取URL*/
        String url = request.getRequestURL().toString();
        //获取IP
        String ip = request.getRemoteAddr();
        //获取类和方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();

        RequesLog requesLog = new RequesLog(url, ip, classMethod, args);
        System.out.println(requesLog);
        logger.info("Request :{}",requesLog);
    }

  /*  @After("pt()")
    public  void doAfter(){
        System.out.println("doAfter");
    }*/
    @AfterReturning(pointcut = "pt()",returning = "result")
    public void doAfterRururn(Object result){
        logger.info("Result ：{}" ,result);
    }

    private  class RequesLog{
        private String url;
        private  String ip;
        private String classMethod;
        private  Object[] args;

        public RequesLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequesLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
